import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/controller/schooladmin.dart';
import 'package:ichinesereader/controller/user.dart';
import 'package:ichinesereader/models/school/StudentToClassDto.dart';
import 'package:ichinesereader/models/student/StudentItem.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';

// ignore: must_be_immutable
class StudentsAddDataGrids extends StatelessWidget {
  StudentsAddDataGrids(this.isSchoolAdmin, this.studentItemsNotInClass);

  final GlobalKey<SfDataGridState> studentGridkey =
      GlobalKey<SfDataGridState>();

  List<StudentItem> studentItemsNotInClass;
  bool isWebOrDesktop = GetPlatform.isMacOS || GetPlatform.isWeb;
  bool isSchoolAdmin;
  List<DataGridRow> dataGridRows = <DataGridRow>[];
  DataGridController _dataGridController = DataGridController();
  SchoolAdminController _schoolAdminController = Get.find();
  UserController _userController = Get.find();
  TextEditingController _searchTextController = new TextEditingController();

  @override
  Widget build(BuildContext context) {
    Log.debug('build StudentsAddDataGrids');

    return Column(children: [
      Row(
        children: [
          ElevatedButton(
              child: Text('Add'.tr),
              onPressed: () {
                if (this._dataGridController.selectedRows.length > 0) {
                  StudentToClassDto data = new StudentToClassDto();
                  if (isSchoolAdmin)
                    data.classId =
                        _schoolAdminController.currentSchoolAdminClass.classId;
                  else
                    data.classId = _userController.currentClass.value.classId;

                  data.studentsUserName = [];
                  for (int i = 0;
                      i < this._dataGridController.selectedRows.length;
                      i++) {
                    var row = _dataGridController.selectedRows[i];
                    var uid = row
                        .getCells()
                        .where((element) => element.columnName == 'Id')
                        .first
                        .value;
                    var student = studentItemsNotInClass
                        .where((e) => e.userId.toString() == uid.toString())
                        .first;
                    data.studentsUserName?.add(student.userName.toString());
                  }

                  if (data.studentsUserName!.length > 0) {
                    _schoolAdminController
                        .addStudentsToClass(data)
                        .then((statusMessage) {
                      if (statusMessage.status == 1000) {
                        Future.delayed(Duration(milliseconds: 500), () {
                          showSnackMsg('Successfully added');
                          // Get.snackbar('Message'.tr, 'Successfully added'.tr,
                          //     backgroundColor: Theme.of(context).primaryColor,
                          //     colorText: Theme.of(context).primaryColorLight,
                          //     snackPosition: SnackPosition.BOTTOM);
                        });
                      } else {
                        Future.delayed(Duration(milliseconds: 500), () {
                          showSnackMsg(
                              'Failed to add students, please try again later.');
                          // Get.snackbar(
                          //     'Message'.tr,
                          //     'Failed to add students, please try again later.'
                          //         .tr,
                          //     backgroundColor: Theme.of(context).primaryColor,
                          //     colorText: Theme.of(context).primaryColorLight,
                          //     snackPosition: SnackPosition.BOTTOM);
                        });
                      }
                    });
                  }
                } else {
                  showSnackMsg('Please choose at least one student');
                }
              }),
          Container(
            width: 240,
            child: TextFormField(
              controller: _searchTextController,
              onFieldSubmitted: (query) {
                if (query.trim() != '') {
                  _schoolAdminController.searchStudentsNotInGivenClass(query);
                }
              },
              decoration: InputDecoration(
                  fillColor: Get.theme.primaryColorLight,
                  prefixIcon: Icon(Icons.search),
                  suffixIcon: IconButton(
                    icon: Icon(Icons.clear),
                    onPressed: () {
                      _searchTextController.text = '';
                      _schoolAdminController.resumeStudentsNotInGivenClass();
                    },
                  ),
                  hintText: 'Search...'.tr,
                  border: InputBorder.none),
            ),
          ),
        ],
      ),
      Expanded(child: _buildDataGrid()),
    ]);
  }

  SfDataGrid _buildDataGrid() {
    if (GetPlatform.isDesktop || GetPlatform.isWeb) isWebOrDesktop = true;

    return SfDataGrid(
      source: StudentDataGridSource(items: studentItemsNotInClass),
      onQueryRowHeight: (row) {
        return row.rowIndex == 0 ? 50.0 : 49.0;
      },
      //设置表头高度
      key: studentGridkey,
      showCheckboxColumn: true,
      allowFiltering: true,
      checkboxColumnSettings: Get.isDarkMode
          ? DataGridCheckboxColumnSettings(
              backgroundColor: Color(0xff0a0e21),
            )
          : DataGridCheckboxColumnSettings(backgroundColor: Colors.blue[50]),
      allowSorting: true,
      allowTriStateSorting: true,
      allowSwiping: true,
      selectionMode: SelectionMode.multiple,
      navigationMode: GridNavigationMode.row,
      controller: _dataGridController,
      endSwipeActionsBuilder:
          (BuildContext context, DataGridRow row, int rowIndex) {
        return GestureDetector(
            onTap: () {
              StudentToClassDto data = new StudentToClassDto();
              if (isSchoolAdmin)
                data.classId =
                    _schoolAdminController.currentSchoolAdminClass.classId;
              else
                data.classId = _userController.currentClass.value.classId;

              data.studentsUserName = [];
              var uid = row
                  .getCells()
                  .where((element) => element.columnName == 'Id')
                  .first
                  .value;
              var student = studentItemsNotInClass
                  .where((e) => e.userId.toString() == uid.toString())
                  .first;
              data.studentsUserName?.add(student.userName.toString());

              _schoolAdminController
                  .addStudentsToClass(data)
                  .then((statusMessage) {
                if (statusMessage.status == 1000) {
                  Future.delayed(Duration(milliseconds: 200), () {
                    showSnackMsg('Successfully added');
                  });
                } else {
                  Future.delayed(Duration(milliseconds: 200), () {
                    showSnackMsg(
                        'Failed to add students, please try again later.');
                  });
                }
              });
            },
            child: Container(
                color: Colors.greenAccent,
                child: Center(
                  child: Icon(Icons.add),
                )));
      },
      columns: <GridColumn>[
        GridColumn(
          columnName: 'UserName',
          width: isWebOrDesktop ? 250 : 180,
          label: buildDataGridColumnLabel('UserName'),
        ),
        GridColumn(
          width: 160,
          columnName: 'FirstName',
          label: buildDataGridColumnLabel('FirstName'),
        ),
        GridColumn(
          columnName: 'LastName',
          width: 160,
          label: buildDataGridColumnLabel('LastName'),
        ),
        GridColumn(
          columnName: 'Class',
          width: isWebOrDesktop ? 180 : 150,
          visible: false,
          label: buildDataGridColumnLabel('Class'),
        ),
        GridColumn(
          columnName: 'Enabled?',
          width: isWebOrDesktop ? 80 : 60,
          visible: false,
          label: buildDataGridColumnLabel('Enabled?'),
        ),
        GridColumn(
          columnName: 'Id',
          width: 10,
          visible: false,
          label: buildDataGridColumnLabel('Id'),
        ),
      ],
    );
  }
}

class StudentDataGridSource extends DataGridSource {
  StudentDataGridSource({required List<StudentItem> items}) {
    dataGridRows = items
        .map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
              DataGridCell<String>(
                  columnName: 'UserName', value: dataGridRow.userName),
              DataGridCell<String>(
                  columnName: 'FirstName', value: dataGridRow.firstName),
              DataGridCell<String>(
                  columnName: 'LastName', value: dataGridRow.lastName),
              DataGridCell<String>(
                  columnName: 'Class',
                  value: dataGridRow.classNames != null
                      ? json.encode(dataGridRow.classNames)
                      : null),
              DataGridCell<bool>(
                  columnName: 'Enabled?',
                  value: dataGridRow.disabled == false ? true : false),
              DataGridCell<String>(columnName: 'Id', value: dataGridRow.userId),
            ]))
        .toList();
  }

  List<DataGridRow> dataGridRows = [];

  @override
  List<DataGridRow> get rows => dataGridRows;

  @override
  DataGridRowAdapter? buildRow(DataGridRow row) {
    //列表隔行Row的颜色 // https://help.syncfusion.com/flutter/datagrid/conditional-styling
    Color setRowBackgroundColor() {
      final int index = effectiveRows.indexOf(row);
      if (index % 2 != 0) {
        return Get.isDarkMode ? Colors.black : Colors.grey[200]!;
      }
      return Colors.transparent;
    }

    return DataGridRowAdapter(
        color: setRowBackgroundColor(),
        cells: row.getCells().map<Widget>((dataGridCell) {
          if (dataGridCell.columnName == 'Class') {
            var tempstr = '';
            if (dataGridCell.value != null &&
                dataGridCell.value.toString().contains("]")) {
              List<String> items =
                  List<String>.from(json.decode(dataGridCell.value.toString()));
              items.forEach((element) {
                tempstr = tempstr + element.toString() + ',';
              });
              tempstr = tempstr.substring(0, tempstr.length - 1);
            } else {
              tempstr = dataGridCell.value != null
                  ? dataGridCell.value.toString().replaceAll("\"", "")
                  : '';
            }
            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: Text(
                  tempstr,
                  overflow: TextOverflow.ellipsis,
                  style: Get.textTheme.bodySmall,
                ));
          } else if (dataGridCell.columnName == 'UserName') {
            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: GestureDetector(
                  onTap: () {},
                  child: Text(
                    dataGridCell.value.toString(),
                    style: Get.textTheme.titleLarge,
                    //style: TextStyle(color: Colors.blue[300], ),
                    overflow: TextOverflow.ellipsis,
                  ),
                ));
          } else {
            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: Text(
                  dataGridCell.value.toString(),
                  overflow: TextOverflow.ellipsis,
                  style: Get.textTheme.bodySmall,
                ));
          }
        }).toList());
  }
}
